package com.zmn.plat.admin.controller.channel.mark;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.logger.LoggerUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.ExcelUtil;
import com.zmn.manager.common.database.annotation.ReadOnlyConnection;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.common.dictionary.ChannelDict;
import com.zmn.plat.common.dictionary.ChannelLevelEnum;
import com.zmn.plat.common.dictionary.ChannelRanKEnum;
import com.zmn.plat.common.dictionary.ChannelTypeEnum;
import com.zmn.plat.model.entity.channel.Channel;
import com.zmn.plat.model.entity.channel.ChannelQuery;
import com.zmn.plat.model.entity.channel.mark.ChannelMark;
import com.zmn.plat.model.entity.channel.mark.ChannelMarkGroup;
import com.zmn.plat.model.entity.channel.mark.ChannelMarkGroupQuery;
import com.zmn.plat.model.entity.channel.mark.ChannelMarkQuery;
import com.zmn.plat.services.interfaces.channel.ChannelService;
import com.zmn.plat.services.interfaces.channel.mark.ChannelMarkGroupService;
import com.zmn.plat.services.interfaces.channel.mark.ChannelMarkService;
import com.zmn.plat.services.interfaces.service.tariff.ServiceTariffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 渠道标示基础查询Controller
 *
 * @author jiafei
 * @since 2021/12/06 11:23
 */
@Slf4j
@RestController
@RequestMapping("/channel/mark")
public class ChannelMarkListController extends PlatBaseController {

    @Resource
    private ChannelMarkService channelMarkService;

    @Resource
    private ChannelMarkGroupService channelMarkGroupService;

    @Resource
    private ChannelService channelService;

    @Resource
    protected ServiceTariffService faultTariffService;

    /**
     * 描述: 查询列表
     *
     * @author jiafei
     * @since 2021/12/06 11:23
     */
    @RequestMapping("/list")
    public ModelAndView list(ChannelMarkQuery query) {

        List<ChannelMark> items = channelMarkService.listPageByQuery(query);

        ModelAndView mv = new ModelAndView("channel/mark/list");
        mv.addObject("items", items);
        mv.addObject("vo", query);

        return mv;
    }

    /**
     * 描述: 详情
     *
     * @author jiafei
     * @since 2021/12/06 11:23
     */
    @RequestMapping("/addEditView")
    public ModelAndView addEditView(@RequestParam(value = "markId", required = false) Integer markId) {

        ChannelMark channelMark;
        if (NumberUtil.isNullOrZero(markId)) {
            channelMark = new ChannelMark();
        } else {
            channelMark = channelMarkService.findById(markId);
        }
        ModelAndView mv = new ModelAndView("channel/mark/detail");
        mv.addObject("channelMark", channelMark);

        return mv;
    }


    /**
     * 描述: 查询管理渠道列表
     *
     * @author jiafei
     * @since 2021/12/06 11:23
     */
    @RequestMapping("/group/list")
    public ModelAndView groupList(ChannelMarkGroupQuery query) {

        List<ChannelMarkGroup> items = channelMarkGroupService.listPageByQuery(query);
        ChannelMark obj = channelMarkService.findById(query.getMarkId());

        ModelAndView mv = new ModelAndView("channel/mark/group/list");
        mv.addObject("items", items);
        mv.addObject("vo", query);
        mv.addObject("obj", obj);
        mv.addObject("markList", channelMarkService.listByQuery(ChannelMarkQuery.builder().status(GlobalConsts.YES).build()));

        return mv;
    }


    /**
     * 描述: 查询管理渠道列表
     *
     * @author jiafei
     * @since 2021/12/06 11:23
     */
    @RequestMapping("/group/assChannels/list")
    public ModelAndView assChannelsList(ChannelQuery query, Integer markId) {

        ChannelMarkGroupQuery markGroupQuery = ChannelMarkGroupQuery.builder().markId(markId).build();
        List<ChannelMarkGroup> checkeds = channelMarkGroupService.listPageByQuery(markGroupQuery);

        ChannelMark mark = channelMarkService.findById(markId);

        ModelAndView mav = new ModelAndView("channel/mark/group/sub/list");

        query.setStatus(GlobalConsts.YES);
        query.setRank(ChannelRanKEnum.CHANNEL_TWO_LEVEL);

        List<Channel> channels = Optional.ofNullable(channelService.listPageByQuery(query, getMcStaffId())).orElse(Collections.emptyList());
        List<Integer> showChannelIds = channels.stream().map(Channel::getChannelId).collect(Collectors.toList());
        List<Integer> checkedIds = checkeds.stream().map(ChannelMarkGroup::getChannelId).collect(Collectors.toList());
        // 当前页面渠道 已关联了的
        List<ChannelMarkGroup> channelMarkGroups = channelMarkGroupService.listPageByQuery(ChannelMarkGroupQuery.builder().channelIds(showChannelIds).build());
        List<Integer> assChannelIds = Optional.ofNullable(channelMarkGroups).orElse(Collections.emptyList()).stream().map(ChannelMarkGroup::getChannelId).collect(Collectors.toList());
        if (CollectionUtil.isNotNullOrEmpty(checkedIds)) {
            assChannelIds.removeAll(checkedIds);
        }

        mav.addObject("query", query);
        mav.addObject("mark", mark);
        mav.addObject("items", channels);
        mav.addObject("plats", GlobalConsts.getPlatList());
        mav.addObject("oneChannels", getOneChannels());
        mav.addObject("checkedIds", checkedIds);
        mav.addObject("assChannelIds", assChannelIds);
        mav.addObject("showChannelIds", showChannelIds);
        mav.addObject("channelTypes", ChannelTypeEnum.enables());
        mav.addObject("channelLevels", ChannelLevelEnum.values());
        mav.addObject("faultTariffs", faultTariffService.listAll());
        mav.addObject("channelAccessModes", ChannelDict.getChannelAccessModeListItems());

        return mav;

    }


    @RequestMapping(value = "outputExcel")
    public void outputExcel(HttpServletResponse response, @ModelAttribute ChannelMarkQuery query) {
        Integer pageSize = getExportPageLimit(response);
        query.setPageSize(pageSize);
        List<ChannelMark> channelMarks = Optional.ofNullable(channelMarkService.listPageByQuery(query)).orElse(Collections.emptyList());
        List<List<String>> collect = channelMarks.stream().map(x -> {
                    List<String> row = new ArrayList<>();
                    row.add(x.getMarkId().toString());
                    row.add(x.getName());
                    row.add(Objects.equals(x.getStatus(), GlobalConsts.YES) ? "启用" : "停用");
                    row.add(x.getUpdater());
                    row.add(DateUtil.dateFormatToString(x.getUpdateTime(), DateUtil.FORMAT_DEFAULT));
                    return row;
                }
        ).collect(Collectors.toList());
        ArrayList<List> lists = Lists.newArrayListWithExpectedSize(channelMarks.size());


        lists.add(Arrays.asList("标示ID", "标示名称", "状态", "操作人", "操作时间"));
        lists.addAll(collect);
        try {
            String name = "渠道标示.xlsx";
            name = new String(name.getBytes(), "ISO8859-1");
            ExcelUtil.export(response, lists, name, "sheet");
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "导出报表出错" + e.getMessage(), e);
        }
    }


    @RequestMapping(value = "/group/outputExcel")
    public void groupOutputExcel(HttpServletResponse response, @ModelAttribute ChannelMarkGroupQuery query) {
        Integer pageSize = getExportPageLimit(response);
        query.setPageSize(pageSize);
        List<ChannelMarkGroup> items = channelMarkGroupService.listPageByQuery(query);
        List<List<Object>> collect = items.stream().map(x -> {
                    List<Object> row = new ArrayList<>();
                    row.add(x.getChannelId());
                    row.add(x.getChannelName());
                    row.add(x.getUpdater());
                    row.add(DateUtil.dateFormatToString(x.getUpdateTime(), DateUtil.FORMAT_DEFAULT));
                    return row;
                }
        ).collect(Collectors.toList());
        ArrayList<List> lists = Lists.newArrayListWithExpectedSize(items.size());


        lists.add(Arrays.asList("渠道ID", "渠道名称", "操作人", "操作时间"));
        lists.addAll(collect);
        try {
            String name = "关联渠道.xlsx";
            name = new String(name.getBytes(), "ISO8859-1");
            ExcelUtil.export(response, lists, name, "sheet");
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "导出报表出错" + e.getMessage(), e);
        }
    }

    /**
     * 获取一级渠道列表
     *
     * @return the one channels
     */
    @ReadOnlyConnection
    protected List<Channel> getOneChannels() {
        return channelService.listOneLevelChannel();
    }





}
